package com.dx.utils;

import com.dx.exception.JwtTokenException;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;

public class JwtUtil {
    public static String createToken(HashMap<String, Object> claims, String secretKey, long ttlMillis) {
        if (claims==null) {
            claims=new HashMap<>();
        }

        JwtBuilder builder = Jwts.builder().
                setClaims(claims).
                signWith(SignatureAlgorithm.HS256,secretKey.getBytes());
        if (ttlMillis>0) {
            long noweMillis = System.currentTimeMillis();
            long expMillis=noweMillis+ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        return builder.compact();

    }

    public static Claims parseToken(String jwtToken,String secretKey) {
        try{
            System.out.println("开始解析token了");
            final Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(jwtToken);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            throw new JwtTokenException("token过期");

        }
        catch (Exception e){
            throw new JwtTokenException("token无效");
        }

    }

    public static void verfyToken(String jwtToken,String secretKey) {

    }
}
